<script lang="ts" setup name="Users">
import { Plus, Upload, Download, Delete } from '@element-plus/icons-vue'
import { fetchUsersPageApi, createUserApi, updateUserApi, deleteUserByIdApi, batchDeleteUsersApi, fetchRolesOfUserApi, assignRolesApi } from '@/api/system/users/index'
import { fetchRolesListApi } from '@/api/system/roles/index'
import { FormInstance, FormRules } from 'element-plus'
import { User } from '@/api/system/users/type'
import { resetForm } from '@/utils/common'
import { Role } from '@/api/system/roles/type';
import { Dept } from '@/api/system/depts/type'
import { getDeptTreeApi } from '@/api/system/depts'

const conditionFold = ref(true)
const toggleConditionFold = () => {
  conditionFold.value = !conditionFold.value
}
const multipleSelection = ref<(string|number)[]>([])
const handleSelectionChange = (users: User[]) => {
    multipleSelection.value = users.map(user => user.id)
}
const tableData = ref<User[]>([])

const current = ref(1)
const size = ref(10)
const handleSizeChange = (val: number) => {
    size.value = val
    fetchUsersList()
}
const handleCurrentChange = (val: number) => {
    current.value = val
    fetchUsersList()
}

const deptTree = ref<Dept[]>()
const defaultProps = {
    label: 'name',
    value: 'id',
}

const queryForm = reactive({
    deptId: '',
    email: '',
    nickname: '',
    phone: '',
})

const total = ref(0)

const fetchUsersList = async () => {
    const res = await fetchUsersPageApi(current.value, size.value, queryForm)
    total.value = parseInt(res.data.data.total)
    tableData.value = res.data.data.records
}

const fetchDeptsTree = async () => {
    const res = await getDeptTreeApi()
    if (res.data.code == 200) {
        deptTree.value = res.data.data
    }
}

const queryFormRef = ref<FormInstance>()
const queryRules = reactive<FormRules>({
    email: [],
    phone: [],
    nickname: []
})

const resetQueryForm = () => {
    resetForm(queryFormRef.value)
    current.value = 1
    fetchUsersList()
}

const drawer = reactive({
    visible: false,
    mode: '',
})
// 
const drawerFormRef = ref<FormInstance>()

const user = ref<User>({
    id: '',
    nickname: '',
    avatar: '',
    address: '',
    email: '',
    phone: '',
    remark: '',
    disabled: false,
    password: '',
    deptId: '',
})
// 添加按钮点击事件
const addClick = () => {
    drawer.visible = true
    drawer.mode = 'add'
}
// 编辑按钮点击事件
const editClick = (rowData: any) => {
    drawer.visible = true
    drawer.mode = 'update'
    nextTick(() => {
        user.value = { ...rowData }
    })
}
// 添加/编辑页面关闭之前处理
const handleClose = (done: () => void) => {
    resetForm(drawerFormRef.value)
    done()
}
// 添加/编辑事件提交
const submit = async () => {
    try {
        if (drawer.mode == 'add') {
            await createUserApi(user.value)
        } else if (drawer.mode == 'update') {
            await updateUserApi(user.value)
        }
        drawer.visible = false
        resetForm(drawerFormRef.value)
        current.value = 1
        fetchUsersList()
        ElMessage({
            message: '提交成功',
            type: 'success',
            plain: true,
        })
    } catch (err) {
        ElMessage({
            message: '提交失败',
            type: 'error',
            plain: true,
        })
    }
}
// 删除单个菜单
const deleteClick = (id: string) => {
    try {
        deleteUserByIdApi(id)
        current.value = 1
        fetchUsersList()
        ElMessage({
            message: '删除成功',
            type: 'success',
            plain: true,
        })
    } catch (err) {
        ElMessage({
            message: '删除失败',
            type: 'error',
            plain: true,
        })
    }
}

// 批量删除
const deleteBatchClick = async () => {
    try {
        await batchDeleteUsersApi(multipleSelection.value)
        fetchUsersList()
        ElMessage({
            message: '删除成功',
            type: 'success',
            plain: true,
        })
    } catch (err) {
        ElMessage({
            message: '删除失败',
            type: 'error',
            plain: true,
        })
    }
}

// 对话框
const dialog = reactive<{
    visible: boolean,
    userId: string|number,
    nickname: string,
}>({
    visible: false,
    userId: '',
    nickname: '',
})
// 所有角色列表
const roleList = ref<Role[]>([])
// 已勾选的角色列表
const selectedRoleList = ref<string[]>([])
// 清空对话框内容
const clearDialogContent = () => {
    dialog.userId = ''
    dialog.nickname = ''
    selectedRoleList.value = []
}

const dialogClose = (done: () => void) => {
    clearDialogContent()
    done()
}

const assignRolesClick = async (rowData: User) => {
    try {
        const res = await fetchRolesOfUserApi(rowData.id)
        selectedRoleList.value = res.data.data.map((role: { id: string; }) => role.id)
        dialog.visible = true
        dialog.userId = rowData.id
        dialog.nickname = rowData.nickname
    } catch (err) {
        ElMessage({
            message: '获取用户的角色信息失败',
            type: 'error',
            plain: true,
        })
    }
}

const assignRolesSubmit = async () => {
    try {
        await assignRolesApi(dialog.userId, selectedRoleList.value)
        dialog.visible = false
        clearDialogContent()
    } catch (err) {
        ElMessage({
            message: '分配角色失败',
            type: 'error',
            plain: true,
        })
    }
}

const fetchRolesList = async () => {
    try {
        const res = await fetchRolesListApi()
        roleList.value = res.data.data
    } catch (err) {
        ElMessage({
            message: '获取角色列表数据出错',
            type: 'error',
            plain: true,
        })
    }
}

onMounted(() => {
    fetchRolesList()
    fetchUsersList()
    fetchDeptsTree()
})
</script>

<template>
    <div h-full box-border w-full flex flex-col gap-row-4>
        <!-- 查询表单 -->
        <div style="box-shadow: var(--el-box-shadow);">
            <el-form :inline="true" :model="queryForm" style="margin: 1rem 1rem 0 1rem" ref="queryFormRef"
                :rules="queryRules">
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="queryForm.email" placeholder="请输入邮箱" clearable />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="queryForm.nickname" placeholder="请输入昵称" clearable />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="queryForm.phone" placeholder="请输入手机号" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchUsersList">查询</el-button>
                    <el-button type="primary" @click="resetQueryForm">重置</el-button>
                    <el-button link type="primary" @click="toggleConditionFold()">
                        <div v-if="conditionFold">
                            展开<i i-ep-arrow-down />
                        </div>
                        <div v-else>
                            收起<i i-ep-arrow-up />
                        </div>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 表格数据 -->
        <div flex-1 overflow-hidden box-border position-relative style="box-shadow: var(--el-box-shadow);" pt-2>
            <div position-absolute w-full h-full flex flex-col overflow-hidden>
                <div flex flex-justify-end box-border p-4>
                    <ElButton :icon="Plus" circle @click="addClick"></ElButton>
                    <ElButton :icon="Upload" circle></ElButton>
                    <ElButton :icon="Download" circle></ElButton>
                    <ElButton :icon="Delete" circle @click="deleteBatchClick"></ElButton>
                </div>
                <div flex-1 overflow-hidden box-border>
                    <ElTable :data="tableData" w-full :border="true" height="100%"
                        @selection-change="handleSelectionChange" :cell-style="{ 'text-align': 'center' }"
                        :header-cell-style="{ 'text-align': 'center' }">
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="nickname" label="昵称" width="120" />
                        <el-table-column prop="email" label="邮箱" width="200" />
                        <el-table-column prop="phone" label="手机号" width="120" />
                        <el-table-column prop="status" label="状态" width="80">
                            <template #default="scope">
                                <ElTag :type="scope.row.disabled ? 'danger' : 'success'">
                                    {{ scope.row.disabled ? '禁用' : '启用' }}
                                </ElTag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="地址" width="200" />
                        <el-table-column prop="createTime" label="创建时间" width="200" />
                        <el-table-column prop="remark" label="备注" width="600" />
                        <el-table-column fixed="right" label="操作" width="120">
                            <template #default="scope">
                                <div flex flex-justify-around flex-items-center>
                                    <el-tooltip content="编辑">
                                        <ElIcon @click="editClick(scope.row)">
                                            <i i-ep-edit />
                                        </ElIcon>
                                    </el-tooltip>
                                    <el-tooltip content="分配角色">
                                        <ElIcon @click="assignRolesClick(scope.row)">
                                            <i i-mdi:account-hard-hat-outline />
                                        </ElIcon>
                                    </el-tooltip>
                                    <ElTooltip content="删除">
                                        <div flex>
                                            <el-popconfirm title="确认删除这条数据吗？" @confirm="deleteClick(scope.row.id)">
                                                <template #reference>
                                                    <ElIcon>
                                                        <i i-ep-delete />
                                                    </ElIcon>
                                                </template>
                                            </el-popconfirm>
                                        </div>
                                    </ElTooltip>
                                </div>
                            </template>
                        </el-table-column>
                    </ElTable>
                </div>
                <!-- 分页 -->
                <div style="box-shadow: var(--el-box-shadow);" p-4>
                    <ElPagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[5, 10, 20, 50]"
                        layout="total,sizes,->,prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>

        </div>

        <!-- 新增/修改抽屉组件 -->
        <el-drawer v-model="drawer.visible"
            :title="drawer.mode == 'add' ? '新增用户' : (drawer.mode == 'update' ? '修改用户' : '')" direction="rtl"
            :before-close="handleClose">
            <el-form :model="user" label-width="auto" ref="drawerFormRef">
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="user.nickname" />
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="user.address" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="user.phone" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-show="drawer.mode == 'add'">
                    <el-input v-model="user.password" />
                </el-form-item>
                <el-form-item label="部门" prop="deptId">
                    <el-tree-select v-model="user.deptId" :data="deptTree" check-strictly :render-after-expand="false" :props="defaultProps" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="user.remark" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="user.disabled" active-text="禁用" inactive-text="启用" inline-prompt
                        style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66" />
                </el-form-item>
            </el-form>
            <template #footer>
                <ElDivider />
                <ElButton size="large" @click="submit">提交</ElButton>
            </template>
        </el-drawer>

        <!-- 分配角色 -->
        <el-dialog v-model="dialog.visible" title="分配角色" width="500" :before-close="dialogClose"
            :close-on-click-modal="false">
            <div flex flex-items-center>
                <span flex-shrink-0 mr-4>账号</span>
                <el-input v-model="dialog.nickname" disabled />
            </div>
            <div mt-4 flex flex-items-center>
                <span flex-shrink-0 mr-4>角色</span>
                <el-select v-model="selectedRoleList" multiple>
                    <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
                </el-select>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialog.visible = false; clearDialogContent();">取消</el-button>
                    <el-button type="primary" @click="assignRolesSubmit">
                        保存
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped></style>